import { useAuthStore } from "@/store/auth";
import axios, { AxiosResponse } from "axios";
import { showToast } from "vant";

const instance = axios.create(getConfig())

instance.interceptors.request.use(
    (request) => {
        const useStore = useAuthStore();
        if (request.url !== undefined) {
            const url = request.url;
            if (!url.startsWith('/auth/login') &&
                !url.startsWith('/auth/register')) {
                request.headers.setAuthorization(useStore.getToken);
            }
        }
        return request; 
    },
    (error) => {
        console.log(error);
        showToast(error);
    }
)

instance.interceptors.response.use(
    (response) => {
        const { code, msg} = response.data as Result;
        if(code === 200) {
            return response.data;
        } else if (code == 2000) {
            return response.data;
        } else if (code == 4500) {
            const authStore = useAuthStore();
            authStore.goLogin();
        } else if (noDisplay.find((i) => i == code) === code) {
            return Promise.reject(msg);
        } else {
            showToast(msg);
            return Promise.reject(new Error(msg || "Error"));
        }
    },
    (error) => {
        if (error.response && error.response.status === 401) {
            console.log('Received 401 Unauthorized:', error.response.data);
            const authStore = useAuthStore();
            authStore.logout();
        } else {
            showToast(error.message || 'Request failed');
        }
        return Promise.reject(error);
    }
)

function getConfig() {
    return {
        baseURL: import.meta.env.VITE_BASE_API,
        timeout: 20000,
        headers: {
            "Content-Type": "application/json;charset=utf-8",
            "Authorization": ""
        }
    };
}

export interface Result extends AxiosResponse {
    code: number;
    msg: string;
    data: any;
}

const noDisplay = [
    6032
]

export default instance;